package com.keruyun.base;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;


public class ProtostuffSerializeUtil<T> {

    public byte[] serialize(final T club) {
        Schema<T> schema = RuntimeSchema.createFrom((Class<T>) club.getClass());
        final LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        try {
            return serializeInternal(club, schema, buffer);
        } catch (final Exception e) {
            throw new IllegalStateException(e.getMessage(), e);
        } finally {
            buffer.clear();
        }
    }
    public T deserialize(final byte[] bytes, Class clazz) {
        Schema<T> schema = RuntimeSchema.createFrom(clazz);
        try {
            T club = deserializeInternal(bytes, schema.newMessage(), schema); if (club != null ) {
                return club;
            }
        } catch (final Exception e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
        return null;
    }

    private <T> byte[] serializeInternal(final T source, final Schema<T> schema, final LinkedBuffer buffer) {
        return ProtostuffIOUtil.toByteArray(source, schema, buffer);
    }
    private <T> T deserializeInternal(final byte[] bytes, final T result, final
    Schema<T> schema) { ProtostuffIOUtil.mergeFrom(bytes, result, schema); return result;
    }
}
